package com.dinnerwithfriends.client.authentication.facebook;

import com.dinnerwithfriends.client.GWTEntryPoint;
import com.dinnerwithfriends.client.authentication.facebook.sdk.FBCore;
import com.dinnerwithfriends.client.authentication.facebook.sdk.JSOModel;
import com.dinnerwithfriends.client.interests.ShowInterests;
import com.dinnerwithfriends.client.model.User;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class FacebookFriendBooks {

	public FacebookFriendBooks(FBCore fbCore, final String friendID) {

		this(fbCore, friendID, false);
	}

	public FacebookFriendBooks(FBCore fbCore, final String friendID,
			final boolean me) {

		fbCore.api("/" + friendID + "/books",
				new AsyncCallback<JavaScriptObject>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(JavaScriptObject result) {

						JSOModel jso = result.cast();
						JsArray array = jso.getArray("data");

						if (array.length() > 0) {

							User friend = GWTEntryPoint.facebookFriends
									.get(friendID);

							String books = "";

							for (int i = 0; i < array.length(); i++) {

								JSOModel j = array.get(i).cast();

								String id = j.get("id");

								String name = j.get("name");

								if (me) {

									friend.getFacebookLikes().put(id, name);

								} else {

									String commonInterest = GWTEntryPoint.facebookUser
											.getFacebookLikes().get(id);

									if (commonInterest != null) {

										books += "<a href='http://facebook.com/"
												+ id
												+ "' target='_blank'>"
												+ name + "</a> &nbsp;";
									}
								}
							}

							if (books.length() > 0) {

								String interests = "";
								if (friend.getFacebookInterests() != null) {

									interests += friend.getFacebookInterests();
								}

								friend.setFacebookInterests(interests
										+ "<br>common books: " + books);
							}

							GWTEntryPoint.facebookFriends.put(friendID, friend);

							if (me) {

								GWTEntryPoint.facebookUser = friend;
							}

							ShowInterests.show();
						}
					}
				});

	}
}
